<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 卡片组件 -->
      <el-card class="box-card">
        <!-- 使用 Tabs 组件完成标签页布局 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addRoleBtn"
              >新增角色</el-button>
            </el-row>
            <!-- 使用 Table 组件实现用户角色的渲染 -->
            <el-table border style="width: 100%" :data="rolesList">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column label="角色名" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="setRoles(scope.row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="editRoles(scope.row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRoles(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination
              :current-page="query.page"
              :page-sizes="[10, 15, 20, 25]"
              :page-size="query.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" class="tab-pane">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form
              label-width="120px"
              style="margin-top: 50px"
              :model="formData"
            >
              <el-form-item label="公司名称">
                <el-input
                  v-model="formData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="formData.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="formData.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="closeFn"
      >
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="roleRules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>

        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="cancleRoles">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="roleSubmit"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogVisible"
        width="50%"
        @close="roleDialogCloseFn"
      >
        <assign-permission
          ref="assignPermission"
          :role-id="roleId"
          :permission-list="permissionList"
          :role-ids-list="roleIdsList"
          @close="roleDialogCloseFn"
          @confirmPermissionEv="confirmPermissionFn"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getRolesAPI,
  getCompanyInfoAPI,
  addRoleAPI,
  getRoleIdAPI,
  updateRoleAPI,
  deleteRoleAPI,
  getPermissionListAPI,
  assignPermAPI
} from '@/api'
import { transTree } from '@/utils'
import { mapGetters } from 'vuex'
import AssignPermission from './component/assignPermission.vue'
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      activeName: 'first',
      query: {
        page: 1, // 当前页面
        pagesize: 10 // 页面显示的条数
      },
      rolesList: [], // 角色列表
      total: 0, // 角色数据总条数
      formData: {}, // 回显公司详情
      showDialog: false, // 控制弹框的隐藏和展示
      isEdit: false, // 控制弹出框是否为编辑
      // 添加角色
      roleForm: {
        name: '',
        description: ''
      },
      // 添加角色验证
      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      dialogVisible: false, // 控制分配权限
      roleId: '', // 点击分配权传出去的id
      permissionList: [], // 权限点数组
      roleIdsList: [] // 传到子组件 回显角色权限
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRolesListFn()
    this.getCompanyInfoFn()
    // 调用获取权限点列表的方法
    this.getPermissionListFn()
  },
  methods: {
    // 获取 角色管理 ->这个用来铺页面
    async getRolesListFn() {
      const res = await getRolesAPI(this.query)
      this.rolesList = res.data.rows
      this.total = res.data.total
    },
    // 获取 公司详情
    async getCompanyInfoFn() {
      const res = await getCompanyInfoAPI(this.companyId)
      this.formData = res.data
    },

    // 获取-权限点列表
    async getPermissionListFn() {
      const res = await getPermissionListAPI()
      this.permissionList = transTree(res.data, '0')
    },

    // 确定添加权限按钮
    roleSubmit() {
      this.$refs.roleForm.validate(async(valid) => {
        if (!valid) return false
        if (this.isEdit) {
          const res = await updateRoleAPI(this.roleForm)
          if (!res.success) return
          console.log(res)
          this.$message.success(res.message)
        } else {
          const res1 = await addRoleAPI(this.roleForm)
          if (!res1.success) return
          console.log(res1)
          this.$message.success(res1.message)
        }
        this.showDialog = false
        this.getRolesListFn()
      })
    },

    // 取消权限按钮
    cancleRoles() {
      this.showDialog = false
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.pagesize = newSize
      this.getRolesListFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getRolesListFn()
    },

    // 设置角色 (分配权限)
    async setRoles(id) {
      this.dialogVisible = true
      this.roleId = id
      const res = await getRoleIdAPI(id)
      this.roleIdsList = res.data.permIds
    },

    // 编辑角色
    async editRoles(rolesId) {
      this.showDialog = true
      this.isEdit = true
      const res = await getRoleIdAPI(rolesId)
      this.roleForm = res.data
    },

    // 删除角色
    async delRoles(rolesId) {
      // 给个弹窗
      const delRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (delRes === 'cancel') return this.$message.info('您取消了删除')

      const res = await deleteRoleAPI(rolesId)
      // 根据返回的状态码进行错误提示
      if (!res.success) return this.$message.error(res.message)
      // 删除成功后的提示
      this.$message.success(res.message)
      if (this.rolesList.length <= 1) {
        this.query.page--
        if (this.query.page === 0) {
          this.query.page = 1
        }
      }
      // 重新获取数据
      this.getRolesListFn()
    },

    // 新增角色的点击事件
    addRoleBtn() {
      this.showDialog = true
      this.isEdit = false
    },

    // 关闭 弹窗时的回调
    closeFn() {
      this.$refs.roleForm.resetFields()
    },

    // 关闭 分配权限时的回调
    roleDialogCloseFn() {
      this.dialogVisible = false
      this.roleIdsList = []
      this.$refs.assignPermission.$refs.tree.setCheckedKeys([])
    },

    // 点击确定 分配权限时的回调
    async confirmPermissionFn(arr) {
      const res = await assignPermAPI({
        permIds: arr,
        id: this.roleId
      })
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.roleDialogCloseFn()
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
